const router = require('koa-router')();
const { query } = require('./../config/dbPool');
const {
  QUERY_SQL_By_Username,
  INSERT_User,
  QUERY_COLLECTION_SQL,
  QUERY_SQL_By_Count,
  INSERT_USER_COLLECTION,
  DELETE_USER_COLLECTION,
  INSERT_BROWSE_SQL,
  QUERY_BROWSE_SQL,
  QUERY_COLLECTION_SQL_By_Uid,
  QUERY_BROWSE_SQL_By_Uid,
  QUERY_Food_id_SQL,
  QUERY_SQL_By_Count_All,
  UPDATE_COLLCTION,
  UPDATE_false_COLLCTION,
  UPDATE_USER_IMG,
  QUERY_COMMUNITY_SQL
} = require('./../config/dbSQL');
const sd = require('silly-datetime');
const jwt = require('jsonwebtoken')
const jwtKoa = require('koa-jwt')
const util = require('util');
const { v4: uuidv4 } = require('uuid');
const verify = util.promisify(jwt.verify)
const secret = 'test'
const fs = require('fs');
const path = require('path');
router.prefix('/users')

//用户注册接口
router.post('/logon', async ctx => {
  let { username, count, password } = ctx.request.body
  // console.log(ctx.request.body)
  const values = [username, count, password]
  const data = await query(QUERY_SQL_By_Username, username);
  if (data.results.length) {
    ctx.body = { type: 'error', message: '用户名已存在' }
  } else {
    await query(INSERT_User, values)
    ctx.body = { type: 'success', code: 0, message: '注册成功' }
  }
})

//用户登录接口
router.post('/login', async ctx => {
  const count = ctx.request.body.count
  const password = ctx.request.body.password
  const data = await query(QUERY_SQL_By_Count_All, count);
  if (data.results.length) {
    if (count && password) {
      let userToken = {
        name: count
      }
      const token = jwt.sign(userToken, secret, { expiresIn: '24h' })  //token签名 有效期
      if (data.results[0].password == password) {
        ctx.body = {
          message: '获取token成功',
          code: 1,
          token,
        }
      } else {
        ctx.body = { type: 'error', message: '账号或密码不正确' }
      }
    } else {
      ctx.body = {
        message: '参数错误',
        ode: -1
      }
    }
  } else {
    ctx.body = { type: 'error', message: '用户不存在' }
  }
})
//登录后获取用户信息接口
router.post('/info', async ctx => {
  const count = jwt.verify(ctx.headers.authorization.split(' ')[1], secret).name
  // console.log(jwt.verify(ctx.headers.authorization.split(' ')[1], secret).name)
  // ctx.body = { type: '', message: '用户' }
  // let food_collect = {}, food_history = {}
  const u_info = await query(QUERY_SQL_By_Count_All, count)
  const user_name = u_info.results[0].username
  const user_img = u_info.results[0].user_img
  const collection = await query(QUERY_COLLECTION_SQL_By_Uid, u_info.results[0].uid)
  const history = await query(QUERY_BROWSE_SQL_By_Uid, u_info.results[0].uid)

  ctx.body = {
    user_name,
    user_img,
    collection,
    history
  }



  // ctx.body={
  //   collection,
  //   history
  // }
  // console.log(uid.results[0].uid)
})


//用户点击菜谱收藏接口
router.post('/collect', async ctx => {
  const count = jwt.verify(ctx.headers.authorization.split(' ')[1], secret).name
  const user = await query(QUERY_SQL_By_Count, count);
  const uid = user.results[0].uid;
  const food_id = ctx.request.body.food_id
  const collect_time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
  const params = [uid, food_id, collect_time]
  const data = await query(QUERY_COLLECTION_SQL, params.slice(0, -1))
  if (data.results.length) {
    await query(UPDATE_false_COLLCTION, food_id)//菜谱表标记位为0
    //取消菜谱收藏
    await query(DELETE_USER_COLLECTION, params.slice(0, -1)).then(res => {
      ctx.body = {
        success: true,
        message: '取消收藏',
      };
    });
  } else {
    const food_info = await query(QUERY_Food_id_SQL, food_id)
    const food_img = food_info.results[0].coverImage
    const food_title = food_info.results[0].title
    const params1 = [uid, food_id, collect_time, food_img, food_title]
    await query(INSERT_USER_COLLECTION, params1).then(res => {
      ctx.body = {
        success: true,
        message: '收藏成功',
      };
    });
    await query(UPDATE_COLLCTION, food_id)//菜谱表标记位为1
  }

})


//用户浏览历史接口
router.post('/browse', async ctx => {
  const count = jwt.verify(ctx.headers.authorization.split(' ')[1], secret).name
  const user = await query(QUERY_SQL_By_Count, count);
  const uid = user.results[0].uid;
  const browsing_time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
  const params = [uid, ctx.request.body.food_id, browsing_time]
  const data = await query(QUERY_BROWSE_SQL, params.slice(0, -1))
  if (data.results.length) {
    ctx.body = {
      status: 200,
      msg: "重复浏览",
    };
  } else {
    const food_info = await query(QUERY_Food_id_SQL, ctx.request.body.food_id)
    const food_img = food_info.results[0].coverImage
    const food_title = food_info.results[0].title
    const params1 = [uid, ctx.request.body.food_id, browsing_time, food_title, food_img]
    await query(INSERT_BROWSE_SQL, params1).then(res => {
      if (res.status === 200) {
        ctx.body = {
          status: 200,
          msg: "操作成功",
        };
      }
    })
  }

})

//用户更改头像接口
router.post('/changeImg', async ctx => {
  const { image } = ctx.request.body;
  const count = jwt.verify(ctx.headers.authorization.split(' ')[1], secret).name
  const user = await query(QUERY_SQL_By_Count, count);
  const uid = user.results[0].uid;
  function saveBase64Image(base64String, filePath) {
    const base64Data = base64String.replace(/^data:image\/\w+;base64,/, '');
    const buffer = Buffer.from(base64Data, 'base64');
    fs.writeFileSync(filePath, buffer);
  }

  function getImageUrl(filename) {
    const baseUrl = 'http://8.130.72.2:3000/images/'; // 替换为你的图片服务器 URL
    return `${baseUrl}${filename}`;
  }

  const base64Image = image; // 替换为你的 base64 图片字符串

  // const imageName = 'image.png'; // 替换为你想要的图片文件名
  const imageName = uuidv4() + '.jpg'
  const dir = path.resolve(__dirname, '..')
  const filePath = path.join(dir, 'public', 'images', imageName);

  saveBase64Image(base64Image, filePath);

  const imageUrl = getImageUrl(imageName);
  const params=[imageUrl,uid]
  await query(UPDATE_USER_IMG,params).then(ctx=>{
    ctx.body={
      status: 200,
      msg:"更改头像成功"
    }
  })
})

//社区详情接口
router.post('/community', async ctx => {
  const community=await query(QUERY_COMMUNITY_SQL)
  ctx.body={
    community
  }
})


module.exports = router
